package com.trolls.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class UploadImageServlet extends HttpServlet implements Servlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5886645089349098848L;
	/**
	 * 
	 */
	private static String UPLOAD_DIRECTORY;
	private ServletFileUpload upload;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// process only multipart requests
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");
		UPLOAD_DIRECTORY = this.getServletContext().getRealPath("images/Troll");
		// resp.setStatus(HttpServletResponse.SC_CREATED);

		// resp.flushBuffer();
		if (ServletFileUpload.isMultipartContent(req)) {

			// Create a factory for disk-based file items
			FileItemFactory factory = new DiskFileItemFactory();

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Parse the request
			try {
				List items = upload.parseRequest(req);
				Iterator it = items.iterator();

				while (it.hasNext()) {
					FileItem item = (FileItem) it.next();
					if (!item.isFormField()
							&& "uploadFormElement".equals(item.getFieldName())) {
						String fileName = item.getName();
						// get only the file name not whole path
						if (fileName != null && checkExtension(fileName)) {
							fileName = FilenameUtils.getName(fileName);
							fileName =UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(fileName);
							
							File uploadedFile = new File(UPLOAD_DIRECTORY, fileName);
							item.write(uploadedFile);
							resp.setStatus(HttpServletResponse.SC_CREATED);
							resp.getWriter().print("["+fileName+"]");
							resp.flushBuffer();
						} else{
							throw new IOException("The format for this image isn't accepted.");
						}
					}
				}

			} catch (Exception e) {
				resp.sendError(
						HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
						"An error occurred while creating the file : "
								+ e.getMessage());
			}

		} else {
			resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
					"Request contents type is not supported by the servlet.");
		}
	}
	protected boolean checkExtension(String ext){
		return FilenameUtils.isExtension(ext, "jpg")
				|| FilenameUtils.isExtension(ext, "png")
				|| FilenameUtils.isExtension(ext, "gif")
				|| FilenameUtils.isExtension(ext, "jpeg")
				|| FilenameUtils.isExtension(ext, "bmp");
	}
	public FileItem getFile(HttpServletRequest request)
			throws FileUploadException {
		List<FileItem> items = upload.parseRequest(request);
		Iterator<FileItem> it = items.iterator();
		FileItem itemReturn = null;
		while (it.hasNext()) {
			FileItem item = (FileItem) it.next();
			if (!item.isFormField()
					&& "uploadFormElement".equals(item.getFieldName())) {
				itemReturn = item;
			}
		}
		return itemReturn;
	}
}